// @Author EthanScriptOn
// @Desc
package service

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/switch_log"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/component"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/dao"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/dto"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/middleware"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/pojo"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/request"
	"github.com/gin-gonic/gin"
)

func Login(param *request.LoginRequest) (token string, err error) {
	if param == nil || !param.IsValid() {
		err = fmt.Errorf("param is invalid")
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	err, info := dao.GetUserInfoByUserName(param.Username)
	if err != nil {
		err = fmt.Errorf("unable to find corresponding user based on: %v", err)
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	if info == nil {
		err = fmt.Errorf("unable to find user")
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	err, consistent := component.ConsistentJudgment(info.Password, param.Password)
	if err != nil {
		err = fmt.Errorf("password verification failed:%v", err)
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	if !consistent {
		err = fmt.Errorf("password error")
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	jwtToken, err := component.CreateJwt(info.UserId)
	if err != nil {
		err = fmt.Errorf("unable to create jwt token:%v", err)
		switch_log.Logger().Error("auth_service/Login", err)
		return
	}
	return jwtToken, nil
}

func GetUserDetail(ctx *gin.Context) (userInfo *dto.UserInformation, err error) {
	value, exists := ctx.Get(middleware.USER_INFO)
	if !exists {
		err = fmt.Errorf("user information not found")
		switch_log.Logger().Error("auth_service/GetUserDetail", err)
		return
	}

	information, ok := value.(*pojo.SrfSwitchUserInformation)
	if !ok {
		err = fmt.Errorf("user information type error")
		switch_log.Logger().Error("auth_service/GetUserDetail", err)
		return
	}
	return convert2UserInformation(information), nil
}

func convert2UserInformation(convert *pojo.SrfSwitchUserInformation) *dto.UserInformation {
	formatStr := "2006-01-02 15:04:05"
	return &dto.UserInformation{
		UserId:      convert.UserId,
		Username:    convert.Username,
		Name:        convert.Name,
		Email:       convert.Email,
		AvatarURL:   convert.AvatarURL,
		LastLoginAt: convert.LastLoginAt.Format(formatStr),
		CreatedAt:   convert.CreatedAt.Format(formatStr),
		UpdatedAt:   convert.UpdatedAt.Format(formatStr),
	}
}
